const { Controller } = require('varal');

const { listToTree } = require('../helpers/function');

class ModuleController extends Controller {
	constructor(app) {
		super(app);

		const ModuleService = require('../services/ModuleService');
		this.serv = new ModuleService();
	}

	async index() {
		const { title } = this.app.fields;
		//const serv = this.app.service('ModuleService');

		return this.serv.get({
			title
		}).then((data) => {
			this.app.json({
				err_code: 0,
				data
			})
		})
	}

	async tree({ fields }) {
		const { exclude_id, type } = fields;

		return this.serv.get({
			attributes: ['id', 'name', 'title', 'type', 'parent_id', 'parent_ids'],
			exclude_id,
			type
		}).then((data) => {
			this.app.json({
				err_code: 0,
				data: listToTree(data, 0)
			})
		})
	}

	async info() {
		const { id } = this.app.fields;
		const data = await this.serv.info({ id });

		this.app.json({
			data
		})
	}

	async delete() {
		const { id } = this.app.fields;

		return this.serv.delete(id).then(() => {
			this.app.json({
				err_code: 0
			})
		})
	}

	async save() {
		const params = this.app.fields;

		return this.serv.save(params).then(() => {
			this.app.json({
				err_code: 0
			})
		}).catch((err) => {
			this.app.json({
				err_code: 1,
				err_msg: err.toString()
			})
		});

	}
}

exports = module.exports = ModuleController;
